package com.lanswon.carlocationsearch.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.json.JSONObject;
import com.lanswon.carlocationsearch.dto.ImportDataDto;
import com.lanswon.carlocationsearch.service.CarService;
import com.lanswon.carlocationsearch.util.ExportExcelUtil;
import com.lanswon.carlocationsearch.vo.QueryVo;
import com.lanswon.carlocationsearch.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @Description
 * @Author zsw
 * @Date 2019/12/5 11:16
 * @Version V1.0
 **/
@RestController
@RequestMapping("car")
@Slf4j
public class CarController {

    @Autowired
    CarService carService;


    @PostMapping("import")
    public Result importExcel(MultipartFile file, HttpServletRequest request) throws Exception{
        Result result = new Result();
        //各种验证excel
        int i = file.getOriginalFilename().lastIndexOf(".xlsx");

        if(i == -1 ){
            result.setCode(500);
            result.setMsg("文件格式错误");
            log.error("文件格式错误");
        }

        if (file == null){
            log.error("文件为空");
            result.setCode(500);
            result.setMsg("文件为空");
            return null;
        }
        ImportParams params = new ImportParams();

        params.setHeadRows(1);
        List<ImportDataDto> list = new ArrayList<>();
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), ImportDataDto.class, params);

        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg(e.getMessage()+",请检查表格内容格式");
            return result;
        }

            for(int a =0;a<list.size();a++){
                ImportDataDto importDataDto = list.get(a);
                if(StringUtils.isEmpty(importDataDto.getCarNum())){
                    log.error("车牌号不能为空");
                    result.setCode(500);
                    result.setMsg("第"+(a+2)+"行A列数据，车牌号不能为空");
                    return result;
                }

                if(importDataDto.getDateTime() ==null){
                    log.error("日期为空");
                    result.setCode(500);
                    result.setMsg((a+2)+"行B列数据，日期不能为空");
                    return result;
                }


            }



        request.getSession().removeAttribute("imporData");
        request.getSession().setAttribute("imporData",list);

        return result;
    }



    @PostMapping("list")
    public Result queryData(@RequestBody QueryVo  queryVo , HttpServletRequest request ){
       Integer count = StringUtils.isNotEmpty(queryVo.getCount())?Integer.valueOf(queryVo.getCount()):3;

        request.getSession().setAttribute("count",count);

        Result result = new Result();
        List<ImportDataDto> list  = ( List<ImportDataDto> )(request.getSession().getAttribute("imporData"));
        if(list == null || list.size() == 0){
            result.setCode(500);
            result.setMsg("请导入数据");
            return result;
        }
        String carNum = queryVo.getCarNum();
        List<JSONObject> carDtoList  = new ArrayList<>();
        if(StringUtils.isNotEmpty(carNum)){
            List<ImportDataDto> listFilter = new ArrayList<>();
            for(ImportDataDto importDataDto :list){
                if(importDataDto.getCarNum().equals(carNum)){
                    listFilter.add(importDataDto);
                }
            }


            carDtoList =carService.queryCPicrecordsByCard1(listFilter, count);
        }else{
            carDtoList=carService.queryCPicrecordsByCard1(list, count);
        }



        result.setData(carDtoList);
        request.getSession().removeAttribute("exportData");
        request.getSession().setAttribute("exportData",carDtoList);
        return result;
    }



    @PostMapping("checkExportExcel")
    public Result  checkExportExcel(HttpServletRequest request) throws Exception {
        Result result = new Result();

        List<JSONObject> carDtoList = (List<JSONObject>) (request.getSession().getAttribute("exportData"));

        if(carDtoList == null || carDtoList.size() ==0 ){
            result.setCode(500);
            result.setMsg("未查询到数据，无法导出");
            return result;
        }

        return result;


    }


    @GetMapping("exportExcel")
    public void  exportExcel(HttpServletResponse response,HttpServletRequest request) throws Exception {

        String fileName = DateFormatUtils.format(new Date(),"YYYYMMdd-HHmmss") + ".xlsx";
        List<JSONObject> carDtoList = (List<JSONObject>)  (request.getSession().getAttribute("exportData"));
        int count = (int)request.getSession().getAttribute("count");
        Workbook workbook = ExportExcelUtil.createWorkbook(carDtoList, count);


        ExportExcelUtil.downLoadExcel(fileName,response,workbook);


    }
}